package com.example.administrator.pomelostreet.HttpUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/2/8.
 */

public class HttpUtil {
    public static HttpUtil httpUtil=new HttpUtil();
    public static OkHttpClient okHttpClient=new OkHttpClient();
    private HttpUtil(){}

    public static HttpUtil getHttpUtil(){
        return httpUtil;
    }

    public static byte[] getDataUseOkHttp(String path){

        try {
            Request request=new Request.Builder()
                    .url(path)
                    .build();
            Call call =okHttpClient.newCall(request);
            Response response = call.execute();
            return response.body().bytes();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

  public static byte[] getData(String path){
      try {
          URL url=new URL(path);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setRequestMethod("GET");
          conn.setConnectTimeout(5000);
          if (conn.getResponseCode()==200){
              ByteArrayOutputStream baos=new ByteArrayOutputStream();
              InputStream inputStream =conn.getInputStream();
              int len=0;
              byte[] by=new byte[1024];
              while ((len=inputStream.read(by))!=-1){
                  baos.write(by,0,len);
                  baos.flush();
              }
            return baos.toByteArray();

          }


      } catch (MalformedURLException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }


      return null;

  }




}
